from xml.dom.minidom import parse
domTree = parse("./data/2016/ABSA16_EN_REST_SB1_TEST.xml")
f = open('./data/2016/16-rest-test.tsv', 'w+')
f.write('qid\ttext_a\ttext_b\tlabel\n')
# 文档根元素
rootNode = domTree.documentElement
# 所有句子
Reviews = rootNode.getElementsByTagName("Review")
print("****所有顾客信息****")
true_term_list = []
multiword_list = []
neu_count = 0
neg_count = 0
pos_count = 0
count = 0
for review_origin in Reviews:
    if review_origin.hasAttribute("rid"):
        sentences = review_origin.getElementsByTagName("sentence")
        for sentence_origin in sentences:
            if sentence_origin.hasAttribute("id"):
                text = sentence_origin.getElementsByTagName("text")[0].childNodes[0].data
                if sentence_origin.getElementsByTagName("Opinions"):
                    aspectTerms = sentence_origin.getElementsByTagName("Opinions")[0]
                    aspectTerm_list = aspectTerms.getElementsByTagName("Opinion")
                    option_list_temp = []
                    for aspectTerm in aspectTerm_list:
                        polarity = aspectTerm.getAttribute("polarity")
                        aspect_term = aspectTerm.getAttribute("target")
                        if aspect_term == 'NULL':
                            continue
                        if aspect_term not in option_list_temp:
                            option_list_temp.append(aspect_term)
                            true_term_list.append(aspect_term)
                            if polarity == 'positive':
                                pos_count += 1
                                polarity = 0
                            elif polarity == 'negative':
                                neg_count += 1
                                polarity = 1
                            elif polarity == 'neutral':
                                neu_count += 1
                                polarity = 2
                            else:
                                print(polarity)
                            f.write(str(count) + '\t' + aspect_term + '\t' + text + '\t' + str(polarity) + '\n')
                            count += 1
                            if ' ' in aspect_term:
                                multiword_list.append(aspect_term)
                sentence_and_apsect = []
print(len(true_term_list))
print(neu_count)
print(pos_count)
print(neg_count)